import http.server
import socketserver
import json
import random
import math
import numpy as np
from nanoid import generate

# 设置服务器的IP地址和端口号
server_ip = '0.0.0.0'
server_port = 8803



class MyHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path.startswith('/random-city'):

            # 生成lod1数据
            lod1_data = self.generate_lod_data(1,0,0)

            lod0_data = {
                "scene": {
                    "name": "scene1",
                    "lodsetting": {
                        "lod1": {
                            "distance": 3500,
                            "name": "city"
                        },
                        "lod2": {
                            "distance": 500,
                            "name": "district"
                        },
                        "lod3": {
                            "distance": 200,
                            "name": "street"
                        },
                        "lod4": {
                            "distance": 120,
                            "name": "building"
                        },
                        "lod5": {
                            "distance": 60,
                            "name": "building"
                        }
                    },
                    "default_camera": [
                        {
                            "id": "01",
                            "view_direction": {
                                "x": 0,
                                "y": 0,
                                "z": 0
                            },
                            "position": {
                                "x": 277,
                                "y": 449,
                                "z": 835
                            },
                            "pov": 55,
                            "depth": 50000
                        }
                    ],
                    "children": [],
                    "default_background": {
                        "color": "#c2d2eb",
                        "colorAlpha": 1,
                        "ambientLight": "0xdddddd",
                        "sunlight": {
                            "color": "0xdddddd",
                            "denity": 0.8,
                            "direction": {
                                "x": 1,
                                "y": 1,
                                "z": 2
                            },
                            "position": {
                                "x": 1000,
                                "y": 1000,
                                "z": 1000
                            }
                        },
                        "weather": "sunny",
                        "shadow": "true"
                    }
                }
            }


            lod0_data["scene"]["children"].append(lod1_data)

            #将lod1数据保存为json文件
            with open("cim_server.json", "w") as f:
                json.dump(lod0_data, f, indent=4)

            print("生成的JSON文件已保存为cim_server.json")

            responce_data=lod0_data

            # 发送响应
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(responce_data).encode())

        else:
            # 默认情况下，使用父类的处理方法
            super().do_GET()
    def generate_lod_data(self,lod_id, parent_x , parent_z):
        lod_prefix = {
            1: "city",
            2: "distinct",
            3: "street",
            4: "building"
        }
    
        max_distance = {2: 2900, 3: 300, 4: 110}
    
        data = {
            "id": generate(size=8),
            "name": f"{lod_prefix[lod_id]}{random.randint(1, 100)}",
            "lod": f"lod{lod_id}",
            "position": {"x": 0, "y": 0, "z": 0},
            "rotation": {"x": 0, "y": 0, "z": 0},
            "model_3d": [
                {
                    "model_url": f"lod{lod_id}.obj",
                    "material_url": f"lod{lod_id}.mtl",
                    "texture_url": "",
                    "shader_url": ""
                }
            ],
            "children": []
        }
    
        if lod_id>1:
            #根据距离随机x和z
            pos_x,pos_y= self.generate_random_point(parent_x,parent_z,max_distance[lod_id])
            data["position"]["x"]=pos_x
            data["position"]["z"]=pos_y
    
    
    
    
        # 添加子节点
        num_children = {1: 20, 2: 5, 3: 20}
        child_lod_id = lod_id + 1
        if child_lod_id <= 4:
            
            for _ in range(num_children[lod_id]):
                child_data = self.generate_lod_data(child_lod_id,data["position"]["x"], data["position"]["z"])
                data["children"].append(child_data)
    
        return data

    def generate_random_point(self,cx, cy, num):
        # 生成在 [-num, num] 范围内的随机坐标
        x = cx + random.uniform(-num, num)
        y = cy + random.uniform(-num, num)
    
        return x, y

    


# 创建多线程服务器并监听指定IP地址和端口号


class ThreadedHTTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass


with ThreadedHTTPServer((server_ip, server_port), MyHandler) as httpd:
    print(f"服务器已启动，监听 {server_ip}:{server_port}")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()


